package com.example.lianguisystem.controller;

import com.alibaba.fastjson.JSON;
import com.example.lianguisystem.VO.sales.TableOptions;
import com.example.lianguisystem.common.FineReportConstant;
import com.example.lianguisystem.common.Result;
import com.example.lianguisystem.entity.*;
import com.example.lianguisystem.mapper.UtilMapper;
import com.example.lianguisystem.mapperLianGui.*;
import com.example.lianguisystem.utils.QRCodeUtil;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/salesOrder")
public class SalesOrderController {

    @Autowired
    private UtilMapper utilMapper;
    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SalesOrderMapper salesOrderMapper;
    @Autowired
    private SOrderMapper sOrderMapper;
    @Autowired
    private SOrderdetailMapper sOrderdetailMapper;

    @Autowired
    private MnfManuorderMapper manuorderMapper;

    @Autowired
    private MnfManuorderdetailMapper manuorderdetailMapper;

    @Autowired
    private LabelMapper labelMapper;

    private String keyPre = "salesOrder:";

    @ApiOperation(value = "设置下拉框，数组选项", notes = "设置下拉框，数组选项")
    @PostMapping("/setSelectionToRedis")
    public Result setSelectionToRedis(@RequestBody Map<String, List<String>> selectionMap) {
        List<String> keyList = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : selectionMap.entrySet()) {
            redisTemplate.opsForValue().set(keyPre + entry.getKey(), JSON.toJSONString(entry.getValue()));
            keyList.add(entry.getKey());
        }

        redisTemplate.opsForValue().set(keyPre + "key", JSON.toJSONString(keyList));
        return Result.success();
    }


    @GetMapping("/queryTableData")
    public Result queryTableData(@RequestParam(value = "username",required = false) String username) {
        String str = "[{\n" +
                "\t\t\t\t\t\tlabel: '客户',\n" +
                "\t\t\t\t\t\tprop: 'client',\n" +
                "\t\t\t\t\t\tinputType: 'combox',\n" +
                "\t\t\t\t\t\toptions: ['A1', 'B2', 'C3'],\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '品号',\n" +
                "\t\t\t\t\t\tprop: 'designNo',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\tdisabled: true,\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '品名',\n" +
                "\t\t\t\t\t\tprop: 'cpTypeNo',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '幅宽',\n" +
                "\t\t\t\t\t\tprop: 'specification',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\tdisabled: true,\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '单价(RMB)',\n" +
                "\t\t\t\t\t\tprop: 'unitPrice',\n" +
                "\t\t\t\t\t\tinputType: 'number',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '订单重量(kg)',\n" +
                "\t\t\t\t\t\tprop: 'orderWeight',\n" +
                "\t\t\t\t\t\tinputType: 'number',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '机台号',\n" +
                "\t\t\t\t\t\tprop: 'workshop',\n" +
                "\t\t\t\t\t\tinputType: 'select',\n" +
                "\t\t\t\t\t\toptions: ['一车间', '二车间', '三车间'],\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '定量(g)',\n" +
                "\t\t\t\t\t\tprop: 'ration',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\tdisabled: true,\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '纹路',\n" +
                "\t\t\t\t\t\tprop: 'texture',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '层数',\n" +
                "\t\t\t\t\t\tprop: 'pilesNum',\n" +
                "\t\t\t\t\t\tinputType: 'select',\n" +
                "\t\t\t\t\t\tdisabled: true,\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '卷重(kg)',\n" +
                "\t\t\t\t\t\tprop: 'pieceWeight',\n" +
                "\t\t\t\t\t\tinputType: 'number',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '直径(cm)',\n" +
                "\t\t\t\t\t\tprop: 'diameter',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '数量(卷)',\n" +
                "\t\t\t\t\t\tprop: 'quantity',\n" +
                "\t\t\t\t\t\tinputType: 'number',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '发货日期',\n" +
                "\t\t\t\t\t\tprop: 'deliveryDate',\n" +
                "\t\t\t\t\t\tinputType: 'date',\n" +
                "\t\t\t\t\t\tformat: 'yyyy-MM-dd',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t},\n" +
                "\t\t\t\t\t{\n" +
                "\t\t\t\t\t\tlabel: '备注',\n" +
                "\t\t\t\t\t\tprop: 'remark',\n" +
                "\t\t\t\t\t\tinputType: 'text',\n" +
                "\t\t\t\t\t\trequired: true\n" +
                "\t\t\t\t\t}\n" +
                "\t\t\t\t]";  // 精简后的示例，后续元素类似处理

        Gson gson = new Gson();
        Type type = new TypeToken<List<TableOptions>>() {
        }.getType();
        List<String> clientList = commonMapper.listStringOfClient();
        List<Map<String, Object>> workshopList = salesOrderMapper.listOfNewWorkshop(username);
//        List<Map<String, Object>> workshopList = salesOrderMapper.listOfWorkshop(username);
//        if (workshopList.size()<= 0) {
//            workshopList = salesOrderMapper.listOfWorkshop(null);
//        }

//        List<String> machineArr = commonMapper.listOfWorkshopOsString();
        List<Map<String, String>> pieceUpsList = new ArrayList<>();
        List<Map<String, String>> pilesNumList = new ArrayList<>();
        for (int i = 0; i <= 3; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("value", i + "");
            map.put("text", i + "");
            pieceUpsList.add(map);
        }
        for (int i = 1; i <= 6; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("value", i + "");
            map.put("text", i + "");
            pilesNumList.add(map);
        }


        String keyStr = redisTemplate.opsForValue().get(keyPre + "key");
        Map<String, List<String>> selectionMap = new HashMap<>();
        List<String> keyList = JSON.parseObject(keyStr, List.class);
        for (String key : keyList) {
            String tempList = redisTemplate.opsForValue().get(keyPre + key);
            List<String> list = JSON.parseObject(tempList, List.class);
            selectionMap.put(key, list);
        }

        List<TableOptions> tableOptionsList = gson.fromJson(str, type);
        for (TableOptions tableOptions : tableOptionsList) {
            if (tableOptions.getLabel().equals("客户")) {
                tableOptions.setOptions(clientList);
                continue;
            }
            if ("机台号".equals(tableOptions.getLabel())) {
                tableOptions.setOptions(workshopList);
                continue;
            }
            if (selectionMap.containsKey(tableOptions.getProp())) {
                tableOptions.setOptions(selectionMap.get(tableOptions.getProp()));
                continue;
            }
            if ("pieceUps".equals(tableOptions.getProp())) {
                tableOptions.setOptions(pieceUpsList);
                continue;
            }
//            if ("machine".equals(tableOptions.getProp())) {
//                tableOptions.setOptions(machineArr);
//                continue;
//            }
            if ("pilesNum".equals(tableOptions.getProp())) {
                tableOptions.setOptions(pilesNumList);
                continue;
            }
        }
        return Result.success(tableOptionsList);
    }


    @ApiOperation(value = "订单开单-查询品号信息", notes = "订单开单-查询品号信息")
    @GetMapping("/queryByCpTypeNo")
    public Result queryByCpTypeNo(@RequestParam(value = "cpTypeNo", required = false) String cpTypeNo) {
        List<Map<String, Object>> mapList = salesOrderMapper.listOfGoodsSelection(cpTypeNo);
        for (Map<String, Object> map : mapList) {
            String tempCpTypeNo = (String) map.get("cpTypeNo");
            String[] result = Arrays.stream(tempCpTypeNo.split("\\s+"))  // 按空格分割
                    .filter(s -> !s.isEmpty())                  // 过滤空字符串
                    .toArray(String[]::new);
            System.out.println(tempCpTypeNo);
            if (tempCpTypeNo.contains("分切")) {
                if (result.length > 2) {
                    map.put("specification", result[2]);
                }
                if (result.length > 3) {
                    map.put("pilesNum", result[3].replace("层", ""));
                }
                if (result.length > 4) {
                    map.put("ration", result[4].replace("克", ""));
                }
            } else {
                map.put("pilesNum", 1);
                if (result.length > 2) {
                    map.put("specification", result[2]);
                }
                if (result.length > 3) {
                    map.put("ration", result[3].replace("克", ""));
                }
            }

        }
        Integer count = mapList.size();
        return Result.success(mapList, count);
    }


    @GetMapping("/preview")
    public Result preview(@RequestParam("id") String id) {
        String qrcodeData = salesOrderMapper.selectQrcodeDataById(id);
        String base64QRCode = QRCodeUtil.getBase64QRCode(qrcodeData);
        return Result.success(base64QRCode);
    }

    @GetMapping("/list/salesOrder")
    public Result listSalesOrder(@RequestParam(value = "recordDate", required = false) String recordDate, @RequestParam(value = "client", required = false) String client) {
        List<SalesOrder> salesOrders = salesOrderMapper.listSalesOrder(recordDate, client.split("-")[0]);
        return Result.success(salesOrders);
    }

    @GetMapping("/querySelection")
    public Result querySelection() {
        List<Map<String, Object>> clientList = commonMapper.listOfClient();
        List<Map<String, Object>> prodNameList = commonMapper.listByProdName(null);
//        List<Map<String, Object>> workshopList = salesOrderMapper.listOfWorkshop();
        Map<String, Object> map = new HashMap<>();
        map.put("client", clientList);
//        map.put("workshop", workshopList);
        return Result.success();
    }

    @GetMapping("/queryClientArr")
    public Result queryClientArr() {
        List<Map<String, Object>> mapList = labelMapper.listOfClient();
        return Result.success(mapList);
    }

    @PostMapping("/submit")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    public Result submit(@RequestBody SalesOrder salesOrder, @RequestParam("printer") String printer) {

        salesOrder.setCreateDate(new Date());
        Map<String, Object> clientMap = commonMapper.selectClientOfSubmit(salesOrder.getClient().split("-")[0]);
        Map<String, Object> userDataMap = commonMapper.selectUserData(salesOrder.getCreateBy());
        Map<String, Object> goodsMap = commonMapper.selectGoodsData(salesOrder.getDesignNo());
        SOrder sOrder = getSOrder(clientMap, userDataMap);
        SOrderdetail sOrderdetail = getSOrderdetail(goodsMap, salesOrder, clientMap);
        sOrder.setAmount(sOrderdetail.getAmount());
        sOrder.setLcamount(sOrderdetail.getAmount());
        MnfManuorder mnfManuorder = null;
        List<MnfManuorderdetail> mnfManuorderdetailList = new ArrayList<>();
        if (salesOrder.getCpTypeNo().contains("分切")) {
            List<Map<String, Object>> goodsBomList = salesOrderMapper.selectGoodsBomPrices((Integer) goodsMap.get("goodsid"));
            if (goodsBomList == null || goodsBomList.size() <= 0) {
                return Result.fail("展开货品失败!请检查该货品是否存在物料清单或对应的物料清单是否已审核。");
            }
            mnfManuorder = getMnfManuorder(goodsMap, userDataMap, salesOrder);
            Double amount = 0.0;
            for (Map<String, Object> goodsBom : goodsBomList) {
                MnfManuorderdetail mnfManuorderdetail = getMnfManuorderdetail(goodsBom, salesOrder);
                mnfManuorderdetailList.add(mnfManuorderdetail);
                amount += mnfManuorderdetail.getAmount();
            }
            mnfManuorder.setAmount(amount);
        }

        synchronized (this) {
            DateTimeFormatter tempDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = LocalDate.now().format(tempDtf);
            String pre = "SO-";
            String soBillCode = getBillCode(pre, "s_order");
            Integer soBillid = commonMapper.selectMaxBiillidByTableName("s_order");

            sOrder.setBillid(soBillid);
            sOrder.setBillcode(soBillCode);

            sOrderdetail.setBillid(soBillid);


            sOrderMapper.insert(sOrder);
            sOrderdetailMapper.insert(sOrderdetail);
            commonMapper.execup_ab_billprint_insert(12, soBillid, soBillCode, format, sOrder.getOpid(), sOrder.getShopid());
            Integer mnfBillid = null;
            String mmBillCode = null;
            if (salesOrder.getCpTypeNo().contains("分切")) {
                pre = "MM-";
                mmBillCode = getBillCode(pre, "mnf_manuorder");
                mnfBillid = commonMapper.selectMaxBiillidByTableName("mnf_manuorder");
                mnfManuorder.setBillid(mnfBillid);
                mnfManuorder.setBillcode(mmBillCode);
                for (MnfManuorderdetail mnfManuorderdetail : mnfManuorderdetailList) {
                    mnfManuorderdetail.setBillid(mnfBillid);
                }
                manuorderMapper.insert(mnfManuorder);
                for (MnfManuorderdetail mnfManuorderdetail : mnfManuorderdetailList) {
                    manuorderdetailMapper.insert(mnfManuorderdetail);
                }
                commonMapper.execup_ab_billprint_insert(42, mnfBillid, mmBillCode, format, mnfManuorder.getOpid(), mnfManuorder.getShopid());
            }
            salesOrder.setOrderBillid(soBillid);
            salesOrder.setOrderBillcode(soBillCode);
            salesOrder.setProcessingBillid(mnfBillid);
            salesOrder.setProcessingBillcode(mmBillCode);
            salesOrderMapper.insert(salesOrder);
            try {
                printer = URLEncoder.encode(printer, "UTF-8").replace("+", "%20");
                //调用url，相当于浏览器携带参数直接打开网址
                String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiFactoryOrder.cpt^&billcode=" + soBillCode + "^&dyj=" + printer;

                Runtime.getRuntime().exec("cmd /c start  " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return Result.success();
    }

    private SOrderdetail getSOrderdetail(Map<String, Object> goodsMap, SalesOrder salesOrder, Map<String, Object> clientMap) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(dtf);
//        Map<String, Object> priceMap = commonMapper.selectPriceByProd(12, (Integer) goodsMap.get("unitid"), format
//                , 0, (Integer) goodsMap.get("goodsid"), (Integer) clientMap.get("traderid"), 0, 0);
        Double quantity = salesOrder.getOrderWeight();

        String workshop = salesOrderMapper.selectMnfWorkshopById(salesOrder.getWorkshop());

//        Double defaultPrice = ((BigDecimal) priceMap.get("DefaultPrice")).doubleValue();
        Double defaultPrice = salesOrder.getUnitPrice();
        SOrderdetail sOrderdetail = new SOrderdetail();
        sOrderdetail.setItemno(2);
        sOrderdetail.setGoodsid((Integer) goodsMap.get("goodsid"));
        sOrderdetail.setAprice(0.0);
        sOrderdetail.setPrice(defaultPrice / 1.13);
        sOrderdetail.setQuantity(quantity);
        sOrderdetail.setDisc(100.0);
        sOrderdetail.setTaxrate(13.0);
        sOrderdetail.setAmount(defaultPrice * quantity);
        sOrderdetail.setLcprice(defaultPrice / 1.13);
        sOrderdetail.setLcunitprice(defaultPrice / 1.13);
        sOrderdetail.setLctaxprice(defaultPrice);
        sOrderdetail.setLctaxamt(formatDouble((defaultPrice - defaultPrice / 1.13) * quantity));
        sOrderdetail.setLcgoodsamt(formatDouble(defaultPrice / 1.13 * quantity));
        sOrderdetail.setLcamount(defaultPrice * quantity);
        sOrderdetail.setUnitid((Integer) goodsMap.get("unitid"));
        sOrderdetail.setUnitquantity(quantity);
        sOrderdetail.setUnitprice(defaultPrice / 1.13);
        sOrderdetail.setUnitqty1(quantity);
        sOrderdetail.setUnitqty2(0.0);
        sOrderdetail.setUnitqty3(0.0);
        sOrderdetail.setExtqty(0.0);
        sOrderdetail.setReferextqty(0.0);
        sOrderdetail.setTaxamt(formatDouble((defaultPrice - defaultPrice / 1.13) * quantity));
        sOrderdetail.setGoodsamt(formatDouble(defaultPrice / 1.13 * quantity));
        sOrderdetail.setRefercount(0);
        sOrderdetail.setReferqty(0.0);
        sOrderdetail.setIoqty(0.0);
        sOrderdetail.setClosed(0);
        sOrderdetail.setUserdef1(workshop);
        sOrderdetail.setUserdef2("");
        sOrderdetail.setUserdef3(salesOrder.getRation());
        sOrderdetail.setRemark("");
        sOrderdetail.setTaxprice(defaultPrice);
        sOrderdetail.setOrigprice(defaultPrice / 1.13);
        sOrderdetail.setOrigtaxprice(defaultPrice);
        sOrderdetail.setIslargess(0);
        sOrderdetail.setReleasedqty(0.0);
        sOrderdetail.setFinishedqty(0.0);
        sOrderdetail.setFrozen(0);
        String deliveryDate = salesOrder.getDeliveryDate();
        LocalDate parse = LocalDate.parse(deliveryDate, dtf);
        Date from = Date.from(parse.atStartOfDay(ZoneId.systemDefault()).toInstant());
        sOrderdetail.setChargedate(from);

        sOrderdetail.setMpsqty(0.0);
        sOrderdetail.setWasterqty(0.0);
        sOrderdetail.setPurrequestqty(0.0);
        sOrderdetail.setUserdef4(salesOrder.getTexture());
        sOrderdetail.setUserdef5(String.valueOf(salesOrder.getPieceWeight()));
        sOrderdetail.setUserdef6(salesOrder.getDiameter());
        sOrderdetail.setUserdef7(salesOrder.getQuantity() + "");

        sOrderdetail.setUserdef8(salesOrder.getPilesNum());
        sOrderdetail.setUserdef9(salesOrder.getSpecification());
        sOrderdetail.setRemark(salesOrder.getRemark());
        return sOrderdetail;
    }

    private SOrder getSOrder(Map<String, Object> clientMap, Map<String, Object> userDataMap) {
        SOrder sOrder = new SOrder();
        sOrder.setBillkind(1);
        sOrder.setBillstate(0);
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = LocalDate.now();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
        Date date = Date.from(zdt.toInstant());
        sOrder.setBilldate(date);
        sOrder.setTraderid((Integer) clientMap.get("traderid"));
        sOrder.setCtraderid((Integer) clientMap.get("traderid"));
        sOrder.setShopid(0);
//        sOrder.setDepartmentid(); 默认不选部门
        sOrder.setPaymethodid(9); // 默认电汇结算方式
        sOrder.setOpid((Integer) userDataMap.get("opid"));
        sOrder.setMoneyid(0);

        localDate = LocalDate.of(2050, 12, 31);
        zdt = localDate.atStartOfDay(zoneId);
        date = Date.from(zdt.toInstant());

        sOrder.setValiddate(date);
        sOrder.setExrate(1.0);
        sOrder.setForwardamt(0.0);
        sOrder.setLcforwardamt(0.0);
        sOrder.setReferamt(0.0);
        sOrder.setRefercount(0);
        sOrder.setShiptype((Integer) clientMap.get("ShipType"));
        sOrder.setContactphone((String) clientMap.get("tel1"));
//        sOrder.setRevdate(date);//发货日期
        sOrder.setClosed(0);
        sOrder.setUpdatetime(new Date());
        sOrder.setSflag(0);
        sOrder.setLinkman((String) clientMap.get("contactor"));
        sOrder.setBillto((String) clientMap.get("Shipto"));
        sOrder.setFinished(0);
        sOrder.setDsorder(0);
        sOrder.setDownloaded(0);
        sOrder.setBillstatus(0);
        sOrder.setAckappr(0);
        sOrder.setDistributorid(0);
        sOrder.setRemark("app申请");
        return sOrder;
    }

    private MnfManuorder getMnfManuorder(Map<String, Object> goodsMap, Map<String, Object> userDataMap, SalesOrder salesOrder) {
        MnfManuorder mnfManuorder = new MnfManuorder();
        mnfManuorder.setBillkind(1);
        mnfManuorder.setBillstate(0);
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = LocalDate.now();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
        Date date = Date.from(zdt.toInstant());
        mnfManuorder.setBilldate(date);
        mnfManuorder.setWorkshopid(salesOrder.getWorkshop());
        mnfManuorder.setGoodsid((Integer) goodsMap.get("goodsid"));
        mnfManuorder.setShopid(0);
        mnfManuorder.setOpid((Integer) userDataMap.get("opid"));
        mnfManuorder.setPlandate(date);
        mnfManuorder.setFinisheddate(date);
        mnfManuorder.setQuantity(salesOrder.getOrderWeight());
        mnfManuorder.setFinishedqty(0.0);
        mnfManuorder.setRefercount(0);
        mnfManuorder.setUsetime(0.0);
        mnfManuorder.setClosed(0);
        mnfManuorder.setUpdatetime(new Date());
        mnfManuorder.setSflag(0);
        mnfManuorder.setReferqty(0.0);
        mnfManuorder.setReferextqty(0.0);
        mnfManuorder.setProcreferqty(0.0);
        mnfManuorder.setProcplanqty(0.0);
        mnfManuorder.setWorkingqty(0.0);
        mnfManuorder.setWasterqty(0.0);
        mnfManuorder.setExtqty(0.0);
        mnfManuorder.setRemark("app申请");
        return mnfManuorder;
    }

    private MnfManuorderdetail getMnfManuorderdetail(Map<String, Object> goodsBom, SalesOrder salesOrder) {
        MnfManuorderdetail mnfManuorderdetail = new MnfManuorderdetail();
        Integer itemno = (Integer) goodsBom.get("itemno");
        mnfManuorderdetail.setItemno(itemno + 1);
        mnfManuorderdetail.setGoodsid((Integer) goodsBom.get("goodsid"));
        mnfManuorderdetail.setAprice(0.0);
        Double pprice = ((BigDecimal) goodsBom.get("pprice")).doubleValue();
        mnfManuorderdetail.setPrice(pprice);
        Double bomQuantity = ((BigDecimal) goodsBom.get("quantity")).doubleValue();
        double quantity = bomQuantity * salesOrder.getOrderWeight();
        mnfManuorderdetail.setQuantity(quantity);
        mnfManuorderdetail.setAmount(pprice * bomQuantity * salesOrder.getOrderWeight());
        mnfManuorderdetail.setUnitid((Integer) goodsBom.get("unitid"));
        mnfManuorderdetail.setUnitquantity(quantity);
        mnfManuorderdetail.setUnitprice(pprice);
        mnfManuorderdetail.setUnitqty1(quantity);
        mnfManuorderdetail.setUnitqty2(0.0);
        mnfManuorderdetail.setUnitqty3(0.0);
        mnfManuorderdetail.setExtqty(0.0);
        mnfManuorderdetail.setReferextqty(0.0);
        mnfManuorderdetail.setTokenqty(0.0);
        mnfManuorderdetail.setTokenamt(0.0);
        mnfManuorderdetail.setWastedqty(0.0);
        mnfManuorderdetail.setWastedamt(0.0);
        mnfManuorderdetail.setRefercount(0);
        mnfManuorderdetail.setReferbilltype(0);
        mnfManuorderdetail.setReferqty(0.0);
        mnfManuorderdetail.setIoqty(0.0);
        mnfManuorderdetail.setPurrequestqty(0.0);
        return mnfManuorderdetail;
    }

    private String getBillCode(String pre, String tableName) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-");
        DateTimeFormatter tempDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(tempDtf);
        pre = pre + LocalDate.now().format(dtf);
        Integer maxSeq = commonMapper.selectMaxSeq(pre, tableName);
        String billcode = pre + "00001";
        if (maxSeq != null) {
            billcode = pre + String.format("%05d", maxSeq + 1);
        }
        return billcode;
    }

    public static Double formatDouble(double value) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return Double.valueOf(bd.toString());
    }
}
